package com.lcf.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.lcf.framework.exception.SysException;
import com.lcf.framework.utils.UserUtils;
import com.lcf.system.dao.MovieUserScoreDao;
import com.lcf.system.dto.MovieUserScoreDTO;
import com.lcf.system.entity.Movie;
import com.lcf.system.entity.MovieUserScore;
import com.lcf.system.service.MovieUserScoreService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 用户电影打分记录(MovieUserScore)表服务实现类
 *
 * @author lcf
 * @since 2025-05-16 22:44:32
 */
@Service("movieUserScoreService")
public class MovieUserScoreServiceImpl extends ServiceImpl<MovieUserScoreDao, MovieUserScore> implements MovieUserScoreService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(MovieUserScoreDTO dto) {
        Movie movie = Db.lambdaQuery(Movie.class).eq(Movie::getId, dto.getMovieId()).one();
        if (movie == null) {
            throw new SysException("电影不存在");
        }

        long useId = UserUtils.getUserId();

        if (Db.lambdaQuery(MovieUserScore.class).eq(MovieUserScore::getMovieId, dto.getMovieId()).eq(MovieUserScore::getUserId, useId).exists()) {
            throw new SysException("请勿重复打分");
        }

        MovieUserScore movieUserScore = BeanUtil.copyProperties(dto, MovieUserScore.class);
        movieUserScore.setUserId(useId);
        movieUserScore.insert();


        int scoreTimes = movie.getScoreTimes() == 0 ? 1 : movie.getScoreTimes() + 1;
        BigDecimal movieScore = (movie.getMovieScore().multiply(BigDecimal.valueOf(movie.getScoreTimes())).add(dto.getMovieScore()))
                .divide(BigDecimal.valueOf(scoreTimes), 2, RoundingMode.HALF_UP);

        Movie movieEdit = new Movie();
        movieEdit.setId(movie.getId());
        movieEdit.setScoreTimes(scoreTimes);
        movieEdit.setMovieScore(movieScore);
        movieEdit.setVersion(movie.getVersion());

        movieEdit.updateById();

        return true;
    }
}

